﻿using CnBlogsCore.Interface;
using CnBlogsCore.Model;
using Newtonsoft.Json;
using RestSharp;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;

namespace CnBlogsCore.Services
{
    public class KbArticleService : IKbArticleSrvice
    {
        public string GetKbArticleDetail(string token, string tokenType, int id)
        {
            var client = new RestClient(Global.CnBlogsUrl.KbArticlesDetailUrl);
            client.Authenticator =
                new RestSharp.Authenticators.OAuth2AuthorizationRequestHeaderAuthenticator(
                    token,
                    tokenType);

            var request = new RestRequest(Global.CnBlogsUrl.KbArticlesDetailArgs).AddUrlSegment("id", id);
            
            var response = client.Execute(request, Method.GET);

            string resultBody = "";

            if (response.StatusCode == HttpStatusCode.OK)
            {
                resultBody = JsonConvert.DeserializeObject<string>(response.Content.ToString());
            }

            return resultBody;
        }

        public  List<KbArticle> GetKbArticles(string token, string tokenType, int pageIndex, int pageSize)
        {
            var client = new RestClient(Global.CnBlogsUrl.KbArticlesUrl);
            client.Authenticator = 
                new RestSharp.Authenticators.OAuth2AuthorizationRequestHeaderAuthenticator(
                    token,
                    tokenType);

            RestRequest request = new RestRequest();  
            request.AddParameter("pageIndex", pageIndex);
            request.AddParameter("pageSize", pageSize);

            var response = client.Execute(request, Method.GET);

            List<KbArticle> kbArticles = null;

            if (response.StatusCode == HttpStatusCode.OK)
            {
                string result = response.Content;
                kbArticles = JsonConvert.DeserializeObject<List<KbArticle>>(result);
            }

            return kbArticles;
        }
    }
}
